{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 套利策略分析\n",
    "\n",
    "本笔记本实现常见套利策略分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import akshare as ak\n",
    "import matplotlib.pyplot as plt\n",
    "from statsmodels.tsa.statespace.tools import cfa_simulation\n",
    "\n",
    "# 设置中文显示\n",
    "plt.rcParams['font.sans-serif'] = ['SimHei']\n",
    "plt.rcParams['axes.unicode_minus'] = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 统计套利策略"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def statistical_arbitrage(pair, lookback=30, z_threshold=2):\n",
    "    \"\"\"\n",
    "    统计套利策略\n",
    "    \n",
    "    Args:\n",
    "        pair: 配对股票DataFrame(两列)\n",
    "        lookback: 回看期\n",
    "        z_threshold: 交易阈值\n",
    "        \n",
    "    Returns:\n",
    "        pd.DataFrame: 包含价差和信号\n",
    "    \"\"\"\n",
    "    try:\n",
    "        # 计算价格比的对数\n",
    "        ratio = np.log(pair.iloc[:,0]/pair.iloc[:,1])\n",
    "        \n",
    "        # 计算移动平均和标准差\n",
    "        ma = ratio.rolling(lookback).mean()\n",
    "        std = ratio.rolling(lookback).std()\n",
    "        \n",
    "        # 计算Z-score\n",
    "        z = (ratio - ma)/std\n",
    "        \n",
    "        # 生成信号\n",
    "        signals = pd.DataFrame(index=pair.index)\n",
    "        signals['spread'] = ratio\n",
    "        signals['z_score'] = z\n",
    "        signals['long_signal'] = (z < -z_threshold).astype(int)\n",
    "        signals['short_signal'] = (z > z_threshold).astype(int)\n",
    "        \n",
    "        return signals.dropna()\n",
    "    except Exception as e:\n",
    "        print(f\"统计套利策略执行失败: {e}\")\n",
    "        return pd.DataFrame()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 主分析流程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例：工商银行(601398)和建设银行(601939)配对\n",
    "stock1 = ak.stock_zh_a_hist(symbol=\"601398\", period=\"daily\", adjust=\"qfq\").set_index('日期')['收盘']\n",
    "stock2 = ak.stock_zh_a_hist(symbol=\"601939\", period=\"daily\", adjust=\"qfq\").set_index('日期')['收盘']\n",
    "pair = pd.concat([stock1, stock2], axis=1).dropna()\n",
    "pair.columns = ['ICBC', 'CCB']\n",
    "\n",
    "# 运行统计套利策略\n",
    "result = statistical_arbitrage(pair)\n",
    "\n",
    "# 绘制结果\n",
    "plt.figure(figsize=(12,6))\n",
    "plt.subplot(211)\n",
    "pair.plot(title='配对股票价格')\n",
    "plt.subplot(212)\n",
    "result['z_score'].plot(label='Z-score')\n",
    "plt.axhline(2, color='r', linestyle='--')\n",
    "plt.axhline(-2, color='g', linestyle='--')\n",
    "plt.title('价差Z-score')\n",
    "plt.legend()\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}